var modifyOrAddFlag;
//初始化数据
$(document).ready(function(){
		$('#win').window('close');
		$(".button_con a" ).removeClass("l-btn-plain");
		$('#searchIsCluster').combobox({
			editable: false,
			valueField: 'id',
		    textField: 'name',
		    onSelect: function(record) {
				$("#searchIsCluster").val(record.id);
		    },
		    data: [{
				"id": "",
				"name": "全部"
			},{
				"id": "2",
				"name": "是"
			},{
				"id": "1",
				"name": "否"
			}]
		    
		});
		var urlParamObj = getParamobjFromUrl();
		var name = urlParamObj.name;
		$('#txtSearchDataSourceName').val(name);
	
		$('#comboxSearchFieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	var allCheck = {'id':'','name':'全部'};
		    	data.content.unshift(allCheck);
		    	return data.content;
		    },
		    onSelect: function(record){
		    	comboxSearchForFieldSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	var allCheck = {'id':'','name':'全部'};
        		    	data.content.unshift(allCheck);
        		    	return data.content;
        		    },
        		    onLoadSuccess:function(){
        		    	comboxSearchForFieldSystemName.combobox('setValue','');
        		    }
                }).load();
		    },
		    onLoadSuccess:function(){
		    	$('#comboxSearchFieldName').combobox('setValue','');
		    }
		});
		
		var comboxSearchForFieldSystemName = $('#comboxSearchForFieldSystemName').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });

 		$('#comboxSearchDatabaseType').combobox({
			url: BASE_URL_KETTLE_DATABASE_TYPE,
			valueField: 'code',
		    textField: 'description',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	var allCheck = {'code':'','description':'全部'};
		    	data._embedded.kettleDatabaseTypes.unshift(allCheck);
		    	return data._embedded.kettleDatabaseTypes;
		    },
		    onLoadSuccess:function(){
		    	$('#comboxSearchDatabaseType').combobox('setValue','');
		    }
		});
		
		
		
		$('#comboxFieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onSelect: function(record){
		    	txtSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	txtSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	var SystemName = $('#txtSystemName').combobox('getData');
        				$("#txtSystemName").combobox('setValue',SystemName[0].id);
        		    }
                }).load();
		    	
		    	
		    	
		    }
		    
		});
		
		
		var txtSystemName = $('#txtSystemName').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
		$('#comboxDatabaseType').combobox({
			url: BASE_URL_KETTLE_DATABASE_TYPE,
			valueField: 'code',
		    textField: 'description',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	return data._embedded.kettleDatabaseTypes;
		    },
			onSelect:function(selected){
				if(selected.description == "Oracle"){
					$('#cluster').show();
				}else{
					$('#cluster').hide();
				}
			}
		    
		});
		
		
		$("#datagrid").datagrid({
//			url : BASE_URL_KETTLE_DATASOURCE_SEARCH +'/findByExample' + '?v=' + Date.parse(new Date()),
//			method:'get',
			autoRowHeight:true,
			nowrap:false,
			pageSize:20,
			singleSelect:true,
			striped:true,
			pageList:[10,20,50,100],
			columns:[[
						{field:'id',width:10,checkbox:true},
						{field:'fieldName',title:'领域',width:100},
						{field:'fieldSystemName',title:'系统',width:100},
						{field:'dataBaseTypeCode',title:'数据库类型',width:100,
							formatter: function(value,row,index){
								return row.kettleDataSource.dataBaseTypeForDisplay
							}
						},
						{field:'isCluster',title:'集群',width:60, formatter: function(value, rowData, rowIndex){
							return value==2?"是":"否";
							}
						},
						{field:'name',title:'数据源名称',width:100,align:'left',
							formatter: function(value,row,index){
								return row.kettleDataSource.name
							}
						},
						{field:'hostName',title:'主机',width:100,
							formatter: function(value,row,index){
								return row.kettleDataSource.hostName
							}
						},
						{field:'port',title:'端口',width:100,
							formatter: function(value,row,index){
								return row.kettleDataSource.port
							}
						},
						{field:'databaseName',title:'数据库名',width:100,
							formatter: function(value,row,index){
								return row.kettleDataSource.databaseName
							}
						},
						{field:'username',title:'账号',width:100,
							formatter: function(value,row,index){
								return row.kettleDataSource.username
							}
						},
						{field:'remark',title:'备注',width:170,align:'left'}
			      ]],
			pagination:true,
			onSelect:function(rowIndex,rowData){
				$("#toolbar_edit").linkbutton('enable');
				$("#toolbar_delete").linkbutton('enable');
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录',
		    onSelectPage: function(pageNumber, pageSize) {
		    	$("#datagrid").datagrid('options').pageNumber = pageNumber;
		    	loadData();
		    },
		    onBeforeRefresh: function(pageNumber, pageSize) {
		    	$("#datagrid").datagrid('options').pageNumber = pageNumber;
		    	loadData();
		    	return false;
		    },
		    onChangePageSize: function(pageSize) {
		    	$("#datagrid").datagrid('options').pageSize = pageSize;
		    	loadData();
		    }
		});
		loadData();
	});

	var g_gridData = null;
	var g_handleCount = 0;

	function loadData(pageIndex) {
		var param = {};
		var options = $("#datagrid").datagrid('options');
		param.page = pageIndex? pageIndex:options.pageNumber-1;
		param.size = options.pageSize;
		param.sort = 'createTime,desc';
		var fieldId = $('#comboxSearchFieldName').combobox('getValue');
		if(fieldId !=""){
			param.fieldId = fieldId;
		}
		
		var fieldSystemId = $('#comboxSearchForFieldSystemName').combobox('getValue');
		if(fieldSystemId !=""){
			param.fieldSystemId = fieldSystemId;
		}
		
		var dataBaseTypeCode = $('#comboxSearchDatabaseType').combobox('getValue');
		if(dataBaseTypeCode !=""){
			param.dataBaseTypeCode = dataBaseTypeCode;
		}
		
		var name = $('#txtSearchDataSourceName').val();
		if(name != ""){
			param.name = name;
		}
		var hostName = $('#txtSearchHostName').val();
		if(hostName != ""){
			param.hostName = hostName;
		}
		
		var databaseName = $('#txtSearchDatabaseName').val();
		if(databaseName != ""){
			param.databaseName = databaseName;
		}
		
		var isCluster = $('#searchIsCluster').combobox('getValue');
		if(isCluster != ""){
			param.isCluster = isCluster;
		}
		
		$.ajax({
			url: BASE_URL_KETTLE_DATASOURCE_SEARCH +'/findByExample' + '?v=' + Math.random(),
			type: 'get',
			dataType: "json",
			data: param,
			contentType: "json",
			success: function(data) {
				if(data && data.content && data.content.length)
				{
					g_gridData = data;
					for(var i = 0; i < data.content.length; i++)
					{		
						if(data.content[i].isCluster == 2){
							var dataSourceName = {dataSourceName:data.content[i].kettleDataSource.databaseName}; 
							handleData(dataSourceName, i);
						}
						else
						{
							g_handleCount++;
							if(g_handleCount >= g_gridData.content.length)
							{
								$("#datagrid").datagrid('loadData', {
									total: g_gridData.totalElements,
									rows: g_gridData.content
								});
							}
						}
					}
				}
				else
				{
					$("#datagrid").datagrid('loadData', {
						total: 0,
						rows: []
					});
				}
			},
			error: function() {
				$.messager.alert("错误","<p>服务异常，查询信息失败，请重新登录或稍后再试！</p>","error");
				$("#datagrid").datagrid('loadData', {
					total: 0,
					rows: []
				});
			}
		});
	}
	
	function handleData(dataSourceName, index) {
		$.ajax({
			url: BASE_URL_KETTLE_DATASOURCE_CRUD + "/analyze",
			asyn: true,
			type: "get",
			data:dataSourceName,
			dataType: "json",
			contentType:"application/json",
			success: function(result){
				g_gridData.content[index].kettleDataSource.hostName=result.host;
				g_gridData.content[index].kettleDataSource.port=result.port;
				g_gridData.content[index].kettleDataSource.databaseName=result.serviceName;
				g_handleCount++;
				if(g_handleCount >= g_gridData.content.length)
				{
					$("#datagrid").datagrid('loadData', {
						total: g_gridData.totalElements,
						rows: g_gridData.content
					});
				}
			},
			error: function() {
				g_handleCount++;
				if(g_handleCount >= g_gridData.content.length)
				{
					$("#datagrid").datagrid('loadData', {
						total: g_gridData.totalElements,
						rows: g_gridData.content
					});
				}
			}
		});
	}

	function add(){
		modifyOrAddFlag = true;
		$('#addForm')[0].reset();
		var fieldName = $('#comboxFieldName').combobox('getData');
		if(fieldName && fieldName.length)
		{
			$("#comboxFieldName").combobox('setValue',fieldName[0].id);
		}
		
		$("#comboxFieldName").siblings(".textbox").children(".textbox-text").val($("#comboxFieldName").combobox('getText'));
		
		setTimeout(function(){
			var fieldSystemName = $('#txtSystemName').combobox('getData');
			$("#txtSystemName").combobox('setValue',fieldSystemName[0].id);
			$("#txtSystemName").siblings(".textbox").children(".textbox-text").val($("#txtSystemName").combobox('getText'));
		},50);
		var databaseType = $('#comboxDatabaseType').combobox('getData');
		for(var i=0; i < databaseType.length; i++)
    	{
    		if(databaseType[i].description == "Oracle")
    		{
    			$("#comboxDatabaseType").combobox('select',databaseType[i].code);
    			break;
    		}
    	}
		$("#comboxDatabaseType").siblings(".textbox").children(".textbox-text").val($("#comboxDatabaseType").combobox('getText'));
		$("#win").window('setTitle','数据库数据源管理-新增');
		$('#win').window('open');
	}
	//新增和修改
	function save(){
		if($("#addForm").form("validate")){
			var row = $('#datagrid').datagrid('getSelected');
			var name = $("#txtDataSourceName").val();
			var hostName = $("#txtHostName").val();
			var port = $("#txtPort").val();
			var databaseName = $("#txtDatabaseName").val();
			var username = $("#txtAcount").val();
			var password = RSAUtils.encryptedString(key,$("#txtPassword").val());
			var remark = $("#remark").val();
			var dataBaseTypeCode = $('#comboxDatabaseType').combobox('getValue');
			var fieldSystemId = $('#txtSystemName').combobox('getValue');
			var jsonData;
			var isCluster = $("#iscluster")[0].checked? 2:1;
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
			if(isCluster==2){
				hostName="";
				port="-1";
				databaseName="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST="+ 
				$("#txtHostName").val() + 
				")(PORT="+$("#txtPort").val()+"))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=" + 
				$("#txtDatabaseName").val() + 
				")(FAILOVER_MODE=(TYPE=SELECT)(METHOD=BASIC)(RETRIES=180)(DELA =5))))"
			}
			if(!modifyOrAddFlag){
				jsonData = {
						kettleDataSourceExId:row.id,
						name:name,
						hostName:hostName,
						port:port,
						databaseName:databaseName,
						username:username,
						password:password,
						remark:remark,
						dataBaseTypeCode:dataBaseTypeCode,
						fieldSystemId:fieldSystemId,
						isCluster:isCluster
				};
				var jsonStr = JSON.stringify(jsonData);
				$.ajax({
					url:BASE_URL_KETTLE_DATASOURCE_CRUD + '/savaOrUpdate',
					type:'post',
					contentType:"application/json",
					data: jsonStr,
					success:function(result){
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
						if(result.errorCode == "SUCCESS")
						{
							$.messager.alert('提示',"<p>修改成功!</p>","info");
							$('#win').window('close');
							loadData();
							//$("#datagrid").datagrid("reload", BASE_URL_KETTLE_DATASOURCE_SEARCH +'/findByExample' + '?v=' + Math.random());
						}
						else if (result.errorCode == "DUPLICATE") 
						{
							$.messager.alert('错误',"<p>修改失败，数据源名称已存在！</p>","error");
						}
						else
						{
							$.messager.alert('错误',"<p>修改失败！</p>","error");
						}
					},
					error:function(xhr,s,err){
						$.messager.alert("错误","<p>服务异常，修改信息失败，请重新登录或稍后再试！</p>","error");	
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
					}
					
					
				});
			}else{
				jsonData = {
						name:name,
						hostName:hostName,
						port:port,
						databaseName:databaseName,
						username:username,
						password:password,
						remark:remark,
						dataBaseTypeCode:dataBaseTypeCode,
						fieldSystemId:fieldSystemId,
						isCluster:isCluster
				};
				var jsonStr = JSON.stringify(jsonData);
				$.ajax({
					url:BASE_URL_KETTLE_DATASOURCE_CRUD + '/savaOrUpdate',
					type:'post',
					contentType:"application/json",
					data: jsonStr,
					success:function(result){
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
						if(result.errorCode == "SUCCESS")
						{
							$.messager.alert('提示',"<p>新增成功!</p>","info");
							$('#win').window('close');
							loadData();
							//$("#datagrid").datagrid("reload", BASE_URL_KETTLE_DATASOURCE_SEARCH +'/findByExample' + '?v=' + Math.random());
						}
						else if (result.errorCode == "DUPLICATE") 
						{
							$.messager.alert('错误',"<p>新增失败，数据源名称已存在！</p>","error");
						}
						else
						{
							$.messager.alert('错误',"<p>新增失败！</p>","error");
						}
					},
					error:function(xhr,s,err){
						$.messager.alert("错误","<p>服务异常，新增失败，请重新登录或稍后再试！</p>","error");	
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
					}
				});
			}
		}
	}
	//修改提示
	function update(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要修改的记录</p>","warning");
		}else{
			modifyOrAddFlag = false;
			$('#addForm')[0].reset();
			$("#comboxFieldName").combobox('setValue',row.fieldId);
			$("#comboxFieldName").siblings(".textbox").children(".textbox-text").val($("#comboxFieldName").combobox('getText'));
			
			setTimeout(function(){
				$("#txtSystemName").combobox('setValue',row.fieldSystemId);
				$("#txtSystemName").siblings(".textbox").children(".textbox-text").val($("#txtSystemName").combobox('getText'));
			},50);
			var dataSourceName = {dataSourceName:row.kettleDataSource.databaseName};
			if(row.isCluster == 2){
				$("#iscluster")[0].checked = "checked";
			}	
			$("#txtHostName").val(row.kettleDataSource.hostName);
			$("#txtDatabaseName").val(row.kettleDataSource.databaseName);
			$("#comboxDatabaseType").combobox('select',row.kettleDataSource.dataBaseTypeCode);
			$("#comboxDatabaseType").siblings(".textbox").children(".textbox-text").val($("#comboxDatabaseType").combobox('getText'));
			$("#txtHostName").val(row.kettleDataSource.hostName);
			$("#txtDataSourceName").val(row.kettleDataSource.name);
			$("#txtPort").val(row.kettleDataSource.port);
			$("#txtAcount").val(row.kettleDataSource.username);
			$("#txtPassword").val(row.kettleDataSource.password);
			$("#remark").val(row.remark);
			$("#win").window('setTitle','数据库数据源管理-修改');
			$('#win').window('open');
		}
	}
	//删除
	function del(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要删除的记录!</p>","warning");
			return;
		}
		var id = row.id;
 		var param = {id:id};
 		$.ajax({
 			url:BASE_URL_KETTLE_DATASOURCE_CRUD + '/search/checkIsCanDelete' + '?v=' + Math.random(),
			dataType:'json',
			type:'get',
			data:param,
			contentType:"application/json",
			success:function(result){
					if (result.isCanDelete==true){
						$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(result){
							if (result){
						 		$.ajax({
									url:BASE_URL_KETTLE_DATASOURCE_CRUD + '/' + row.id + '?v=' + Math.random(),
									dataType:'json',
									type:'delete',
									async:false,
									contentType:"application/json",
									timeout:30000,
									success:function(){
										$.messager.alert('提示',"<p>删除成功!</p>","info");
										loadData();
										//$("#datagrid").datagrid("reload");
									},
									error:function(xhr,s,err){
										$.messager.alert('错误',"<p>删除失败!</p>","error");
									}
						 		});
							}
						});
					}else{
						$.messager.alert('错误','<p>删除失败！当前操作的数据库数据源被引用，不允许删除！</p>','error');
					}
				}
 			});
		
	}
	
	//导入
	$('#import_link').window({
		width:465,
		modal:true,
		minimizable:false,
		maximizable:false,
		collapsible:false
	});
	$('#import_link').window('close');  //关闭窗口
	//导入
	function import_link()
	{
		$('#import_link').window('open'); 
	}
	
	function rePage(){
		$('#win').window('close');
		loadData();
		//$("#datagrid").datagrid("reload", BASE_URL_KETTLE_DATASOURCE_SEARCH +'/findByExample' + '?v=' + Math.random());
	}
	
	function search(){
		loadData();
		//$('#datagrid').datagrid('load');
	}
	
	function clear(){
		
	}
	
	function testLink(){
		var dataBaseTypeCode = $('#comboxDatabaseType').combobox('getText');
		var hostName = $("#txtHostName").val();
		var port = $("#txtPort").val();
		var databaseName = $("#txtDatabaseName").val();
		var username = $("#txtAcount").val();
		var password = RSAUtils.encryptedString(key,$("#txtPassword").val());
		var isCluster = $("#iscluster")[0].checked? 2:1;
		
		if($("#txtHostName,#txtPort,#txtDatabaseName,#txtAcount,#txtPassword").validatebox("isValid")){
			$("#progressbar, #progressbar_tips").fadeIn();
			loading_point.timer = setInterval(loading,200);
			$.ajax({
				url:BASE_URL_KETTLE_DATASOURCE_CRUD + '/link/dataBase',
				type:'get',
				dataType:'html',
				data: {"dataBase":dataBaseTypeCode,"host":hostName,"port":port,"userCode":username,"password":password,"dataSourceName":databaseName,"isCluster":isCluster},
				success:function(result){
					$("#progressbar, #progressbar_tips").fadeOut();
					clearInterval(loading_point.timer);
					$.messager.alert('提示',result,"info");
				},
				error: function(){
					$("#progressbar, #progressbar_tips").fadeOut();
					clearInterval(loading_point.timer);
					$.messager.alert('提示',"<p>服务异常，测试连接请求失败</p>","info");
				}
			});
		}else{
			$.messager.alert('错误',"<p>请输入完整的信息!</p>","error", function(){
				$("#txtHostName.validatebox-invalid,#txtPort.validatebox-invalid,#txtDatabaseName.validatebox-invalid,#txtAcount.validatebox-invalid").eq(0).focus();
			});
			
		}
	}
	
	var loading_point = {
			timer:null,
			len:3,
			count:0
		};
	function loading()
	{
	 	if(loading_point.count < loading_point.len)
		{
			loading_point.count++;
			$("#progressbar_point").text($("#progressbar_point").text() + ".");
		}else
		{
			loading_point.count = 0;
			$("#progressbar_point").text("");
		}	
	}
	
